package cn.yuanqiao.web.controller.archive.singleSignOn;

import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.singleSignOn.util.SymmetricEncryption;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/archive/sso")
public class SSOController extends BaseController {

    @Resource
    private SymmetricEncryption symmetricEncryption;

    @Autowired
    private ITenantSysConfigService sysConfigService;

    //获取单点的path
    @PostMapping("/getPath")
    public AjaxResult getPath() {
        //获取path
        String ssoPath = sysConfigService.selectConfigByKey("SSO_PATH");
        if (StringUtils.isEmpty(ssoPath)) {
            throw new ServiceException("系统参数错误SSO_PATH未找到配置！");
        }
        String secretKey = sysConfigService.selectConfigByKey("SECRET_KEY");

        if (StringUtils.isEmpty(secretKey)) {
            throw new ServiceException("系统参数错误SECRET_KEY未找到配置！");
        }

        Map map = new HashMap();
        map.put("path", ssoPath);
        map.put("token", symmetricEncryption.Encrypt(SecurityUtils.getUserId().toString(), secretKey));

        return success(map);
    }

    //验证该用户是否存在
    @PostMapping("/checkUser")
    public AjaxResult checkUser() {
        //获取path
        String url = sysConfigService.selectConfigByKey("CHECK_USER_URL");
        if (StringUtils.isEmpty(url)) {
            throw new ServiceException("系统参数错误CHECK_USER_URL未找到配置！");
        }
        String secretKey = sysConfigService.selectConfigByKey("SECRET_KEY");

        if (StringUtils.isEmpty(secretKey)) {
            throw new ServiceException("系统参数错误SECRET_KEY未找到配置！");
        }
        RestTemplate restTemplate = new RestTemplate();
        // 请求地址、请求参数、HTTP响应被转换成的对象类型
        Map param = new HashMap();
        param.put("token", symmetricEncryption.Encrypt(SecurityUtils.getUserId().toString(), secretKey));
        Map map = new HashMap();
        try {
            map = restTemplate.postForObject(url, param, Map.class);
        } catch (Exception e) {
            throw new ServiceException("系统参数错误SECRET_KEY配置错误！");
        }
        if (map == null) throw new ServiceException("系统参数错误SECRET_KEY配置错误！");
        return AjaxResult.success(map);
    }


}
